package cn.loioi.distribution.db;

import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

import cn.loioi.distribution.db.sql.TableSQL;

public class DbManger {
	protected DataSource dataSource;

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}

	public DbConnoction getConnoction() throws SQLException {
		return new DbConnoction(dataSource);
	}

	public void createTable() throws Exception {
		this.transactionExecute((connection) -> {
			TableSQL sql = new TableSQL();

			Statement statement = connection.createStatement();
			statement.addBatch(sql.getTableCfg());
			statement.addBatch(sql.getTableLevel());
			statement.addBatch(sql.getTableMember());

			statement.executeBatch();

			return null;
		});
	}

	/**
	 * 执行非事务查询
	 * @param execute
	 * @return
	 * @throws Exception
	 */
	public <B> B execute(DbExecute<B> execute) throws Exception {
		DbConnoction connoction = getConnoction();

		B result = null;
		try {
			// 执行查询
			result = execute.execute(connoction);
		} catch (Exception e) {
			throw e;
		} finally {
			if (connoction != null) connoction.close();
		}

		return result;
	}

	/**
	 * 执行事务查询
	 * @param execute
	 * @return
	 * @throws Exception
	 */
	public <B> B transactionExecute(DbExecute<B> execute) throws Exception {
		DbConnoction connoction = getConnoction();

		B result = null;
		try {
			// 设置不自动提交
			connoction.setAutoCommit(false);
			// 执行查询
			result = execute.execute(connoction);
			// 判断是否需要回滚
			if (connoction.isRollbackOnly()) {
				connoction.rollback();
			} else {
				connoction.commit();
			}
		} catch (Exception e) {
			connoction.rollback();

			throw e;
		} finally {
			if (connoction != null) connoction.close();
		}

		return result;
	}
}
